package com.yx.li.webviewdemo;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BasicUsageActivity extends AppCompatActivity implements JsBridge {

    private WebView mWebView;
    private TextView mResult;
    private EditText mEt;
    private Button mBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_usage);
        initView();
    }

    private void initView() {

        mWebView = findViewById(R.id.webview);
        mResult = findViewById(R.id.result);
        mEt = findViewById(R.id.et);
        mBtn = findViewById(R.id.btn);

        //允许webview加载js代码
        mWebView.getSettings().setJavaScriptEnabled(true);

        //给webview添加js接口
        mWebView.addJavascriptInterface(new ImoocJsInterface(this), "imoocLauncher");

        mWebView.loadUrl("file:///android_asset/index.html");

        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = mEt.getText().toString();
                mWebView.loadUrl("javascript:if(window.remote){window.remote('" + text + "')}");
            }
        });

        //打开允许调试的开关
        mWebView.setWebContentsDebuggingEnabled(true);

    }

    @Override
    public void setTextValue(final String string) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mResult.setText(string);
            }
        });
    }

}
